package com.cmpan.networkdisk.controller;

import com.cmpan.networkdisk.service.DiskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;


/**
 * ClassName:DownloadController
 * Package:com.cmpan.networkdisk.controller
 * Description:
 *
 * @Date:2020/7/8 17:08
 * @com.chuangmei
 */
@Controller
@RequestMapping("/download")
public class DownloadController {

    @Autowired
    private DiskService diskService;

    //日志
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @GetMapping("/down/{id}/{filename}")
    public @ResponseBody String download
            (@PathVariable String id, @PathVariable String filename, HttpServletResponse response ) throws UnsupportedEncodingException {


        //得到path
        String path = diskService.selectPathById(Long.valueOf(id));
        //File
        File file = new File(path);
        //获取大小
        int size = (int)file.length();

        //输出
//        System.out.println("下载id: " + id);
//        System.out.println("下载文件名: " + filename);
//        System.out.println("下载文件大小: " + size);

        if (path != null){
            //如果文件存在
            if (file.exists()){
                //设置文件名
                response.addHeader("Content-Disposition", "attachment;fileName="  + new String(filename.getBytes("utf-8"),"iso-8859-1"));
                //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
                response.setContentType("multipart/form-data");
                response.setContentLength(size);
                //byte
                byte[] buffer = new byte[1024];
                //input
                FileInputStream fileInputStream = null;
                BufferedInputStream bufferedInputStream = null;
                try {
                    fileInputStream = new FileInputStream(file);
                    bufferedInputStream = new BufferedInputStream(fileInputStream);
                    //out
                    OutputStream outputStream = response.getOutputStream();
                    //read
                    int count =  bufferedInputStream.read(buffer);
                    while(count != -1){
                        outputStream.write(buffer,0,count);
                        count = bufferedInputStream.read(buffer);
                    }
                    outputStream.flush();
                    return "Success";
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally{
                    if (bufferedInputStream != null){
                        try {
                            bufferedInputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fileInputStream != null){
                        try {
                            fileInputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }

        //日志
        logger.info("downloadPath: {}",filename);

        return "Failed";
    }

}
